package com.yb.guigu.pick.security.config;

import com.yb.guigu.pick.security.handler.GuiguPickAccessDeniedHandler;
import com.yb.guigu.pick.security.handler.GuiguPickAuthenticationEntryPoint;
import com.yb.guigu.pick.security.bean.WhiteListProperties;
import com.yb.guigu.pick.security.filter.GuiguPickUserAuthenticationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 19:25
 * FileName: ResourceServerConfig
 * Description:
 */

@Configuration
@EnableWebSecurity
@Slf4j
@EnableMethodSecurity(securedEnabled = true,proxyTargetClass = true)
@EnableConfigurationProperties(WhiteListProperties.class)
public class ResourceServerConfig {

    @Bean
    GuiguPickUserAuthenticationFilter guiguPickUserAuthenticationFilter(){
        return new GuiguPickUserAuthenticationFilter();
    }

    @Bean
    AuthenticationEntryPoint authenticationEntryPoint(){
        return new GuiguPickAuthenticationEntryPoint()  ;
    }


    @Bean
    AccessDeniedHandler accessDeniedHandler(){
        return new GuiguPickAccessDeniedHandler();
    }

    @Autowired
    WhiteListProperties whiteListProperties;

    @Value("${spring.application.name:UNKNOWN}")
    private String appName;

    @Bean
    @Order(1)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> authorizationManager) throws Exception {


        http.authorizeHttpRequests().anyRequest().access(authorizationManager);


        http.addFilterBefore(guiguPickUserAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler());

        http.csrf().disable();

        return http.build();
    }



}
